﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class ItemController : AsyncCommonControllerVersion2
    {        
        public  ActionResult Index(string search)
        {            
            return View();
        }

        public async Task<ActionResult> Items(Search search = null)
        {
            string search_ITEM_NAME = null;
            string search_EXT_KEY = null;
            string search_ARTICLE = null;
            bool search_IS_ALL = false;
            
            if (search != null)
            {
                if (!String.IsNullOrEmpty(search.EXT_KEY))
                    search_EXT_KEY = search.EXT_KEY;
                if (!String.IsNullOrEmpty(search.ITEM_NAME))
                    search_ITEM_NAME = search.ITEM_NAME;
                if (!String.IsNullOrEmpty(search.ARTICLE))
                    search_ARTICLE = search.ARTICLE;
                if (!String.IsNullOrEmpty(search.IS_ALL))
                    search_IS_ALL = true;
            }
            var data = await EdexContext.GetItems(search_ITEM_NAME, search_EXT_KEY, search_ARTICLE, search_IS_ALL);            
            return PartialView(data.Data);
        }       
               
        public async Task<ActionResult> Item(Guid id)
        {
            var data = await EdexContext.GetItemDetails(id);
            return View(data.Data.SingleOrDefault());
        }

        [HttpPost]
        public async Task<ActionResult> Save(EdexApiClient.WH_ITEMS record)
        {            
            if (record.GUID_RECORD == null || record.GUID_RECORD == Guid.Empty)
                await this.EdexContext.AddItem(record);
            else
                await this.EdexContext.UpdateItem(record);

            return Json(new EdexApiClient.CommonApiResponse());
        }

        [HttpPost]
        public async Task<ActionResult> Delete(Guid ITEM_GUID)
        {
            await EdexContext.DeleteItem(ITEM_GUID.ToString());
            return Json(new EdexApiClient.CommonApiResponse());
        }

        public class Search
        {            
            public String ITEM_NAME { get; set; }
            public String EXT_KEY { get; set; }
            public String ARTICLE { get; set; }
            public String IS_ALL { get; set; }
        }       
    }
}
